package com.fingard.dsp.bank.directbank.mufg01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptData;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptDataHelper;
import com.fingard.dsp.bank.directConfig.ReceiptProConfig;
import com.fingard.dsp.bank.directbank.bankInterface.IReceiptPro;
import com.fingard.dsp.bank.directbank.fngrd01.util.StringHelper;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.io.FileHelper;
import com.fingard.util.PdfGenerateUtil;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.math.BigDecimal;
import java.util.Date;

public class MUFG01ReceiptPro extends MUFG01Base implements IReceiptPro {

    public RetAtsReceipt qryReceiptOneDay_Xml(ReceiptProConfig pConfig,ReqQryReceipt pReqReceipt, Date pOneDay) throws Exception {
        try {
            int dowTotalNum=0;//下载总数
            int qryTotalNum=0;//查询总数
            String pageFlag="";//下一页标识
            boolean pageResult=false;//分页结束标识
            while (!StringHelper.isNullOrEmpty(pageFlag) || !pageResult){//分页循环查询
                //拼接请求报文
                MUFG01Header header=new MUFG01Header();
                header.transCode="h2h.001.003";
                header.pkgNo = getQryTransID();
                XmlTextWriter xmlReq = new XmlTextWriter();
                writeReqHeader(xmlReq,header);
                xmlReq.writeStartElement("req");
                xmlReq.writeElementString("accNo",pReqReceipt.actNum);//帐号
                xmlReq.writeElementString("beginDate",Format.Date10Format.format(pOneDay));//查询开始日期
                xmlReq.writeElementString("endDate",Format.Date10Format.format(pOneDay));//查询结束日期
                xmlReq.writeElementString("amount","");//金额
                xmlReq.writeElementString("corpSerial","");//支付指令ID
                xmlReq.writeElementString("terminalNo","");//终端编码
                xmlReq.writeElementString("info2","");//对方名称
                xmlReq.writeElementString("pageFlag",pageFlag);//下页标识
                xmlReq.writeEndDocument();
                //请求银行并获取响应结果
                String[] resutlt = sendToBank(xmlReq.toXmlString());
                //处理响应报文
                if(resutlt[0].length()==0){
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(resutlt[1], tmpSbMsg);
                    if(tmpBkReader!=null) {
                        String acceptFlag=tmpBkReader.getFirstText("/h2h/respInfo/acceptFlag");//报文受理状态
                        String respCode = tmpBkReader.getFirstText("/h2h/respInfo/respCode");//返回结果码
                        String respInfo = tmpBkReader.getFirstText("/h2h/respInfo/respMsg");//返回结果说明
                        if("1".equals(acceptFlag)){//受理成功
                            String pageFlagRsp=tmpBkReader.getFirstText("/h2h/resp/pageFlag");//下一页标识
                            if(!StringHelper.isNullOrEmpty(pageFlagRsp)){
                                pageFlag=pageFlagRsp;
                            }else {
                                pageResult=true;
                            }
                            if ("1".equals(tmpBkReader.getFirstText("/h2h/resp/statusFlag"))) {//查询处理状态 1有 -1无
                                while (tmpBkReader.read("/h2h/resp/row")){
                                    qryTotalNum++;
                                    String fileName=tmpBkReader.readedXElement.getSingleTextNotNull("fileName");//回单文件名
                                    String fileValue=tmpBkReader.readedXElement.getSingleTextNotNull("fileValue");//回单文件内容
                                    //========电子回单文件下载：同步下载，只记录成功下载的数据========
                                    String localSaveSir=pConfig.getValueAsString("localSaveDir");
                                    String localSavFilePath=localSaveSir+File.separator+fileName;
                                    int result=createPdf(fileName,fileValue,localSaveSir);
                                    if(result==1 && FileHelper.existFile(localSavFilePath)){
                                        //记录回单数据
                                        String[] arg =PdfGenerateUtil.readFileOfPDF(localSavFilePath).split("\r\n");
                                        if(arg.length>22){
                                            String uniqueSeqId=Integer.parseInt(Format.Date8Format.format(pOneDay))+pReqReceipt.actNum+arg[21].trim();
                                            ReceiptData eachData = new ReceiptData();
                                            /**回单唯一标识（在银行端的唯一标识（该账号的唯一），如招行的打印实例号）*/
                                            eachData.istNbr=uniqueSeqId;
                                            /**回单关联号（回单编号）*/
                                            eachData.receiptNo=uniqueSeqId;
                                            /**业务参考号*/
                                            eachData.busRef=uniqueSeqId;
                                            /**本方账号*/
                                            eachData.ownAct=pReqReceipt.actNum;
                                            /**银行代码，如工行102*/
                                            eachData.bank="561";
                                            /**线路代码（来源渠道），如工行直联ICBC02*/
                                            eachData.srcSys=this.bankFront.bankCode;
                                            /**日期*/
                                            eachData.busDate=Integer.parseInt(Format.Date8Format.format(pOneDay));
                                            /**对方账号*/
                                            eachData.oppActNum=arg[18].replaceAll("详细信息4","").trim();
                                            /**对方户名*/
                                            eachData.oppActName=arg[16].replaceAll("详细信息2","").trim();
                                            /**交易方向*/
                                            String cdFlag=arg[12].replaceAll("借记/贷记","").trim();
                                            if("借记".equals(cdFlag)){
                                                eachData.moneyWay="1";
                                            }else if("贷记".equals(cdFlag)){
                                                eachData.moneyWay="2";
                                            }
                                            /**币种*/
                                            eachData.cur=convertCurToATS(arg[5].replaceAll("币种","").trim());
                                            /**金额*/
                                            eachData.amount=new BigDecimal(arg[13].replaceAll("金额","").replaceAll(",","").trim());
                                            /**用途*/
                                            eachData.purpose=arg[17].replaceAll("详细信息3","").trim();
                                            /**回单文件--本地文件相对路径*/
                                            eachData.localFile=pConfig.getPathRelativeToMain(localSavFilePath);
                                            /**源文件路径*/
                                            eachData.srcFile=localSavFilePath;
                                            /**回单文件类型*/
                                            eachData.fileType="1";
                                            /**下载状态：指从银行下载该回单文件的状态，1未下载；2已下载；3下载失败；4下载中*/
                                            eachData.downState="2";
                                            /**下载时间*/
                                            eachData.downTime=new Date();
                                            /**下载信息，如果失败则为失败原因*/
                                            eachData.downInfo="下载成功";
                                            /**上传状态：指文件从银行端下载完成后，上传至ftp或ats或oss或客制化文件服务的状态，1未上传；2已上传；3上传失败；4上传中*/
                                            eachData.upState="1";
                                            /**推送状态：指文件上传完成后，回单数据推送至ats或客制化平台的状态，1未推送；2已推送；3推送失败；4推送中*/
                                            eachData.pushState="1";
                                            /**创建时间*/
                                            eachData.createdOn=new Date();
                                            /**最后修改时间*/
                                            eachData.lastModifiedOn=new Date();
                                            /**版本号*/
                                            eachData.rowVersion=1;
                                            ReceiptDataHelper  receiptHelper = new ReceiptDataHelper(reqHeader.tenant, eachData.getBusDate());
                                            //回单数据记录入库
                                            int inRe = receiptHelper.insertIfNotExist(eachData);
                                            if(inRe>0){
                                                dowTotalNum++;
                                            }else{
                                                WriteBankLogLn(eachData.receiptNo+"写入数据库，影响行数："+inRe);
                                            }
                                        }else{
                                            WriteBankLogLn("回单"+localSavFilePath+"文件格式异常，请联系维护人员");
                                        }
                                    }else{
                                        WriteBankLogLn("回单"+localSavFilePath+"文件下载记录失败，需要重新查询回单");
                                    }
                                }
                            }else {
                                WriteBankLogLn("根据查询条件没有得到对象记录");
                            }
                        }else {//受理未响应或受理失败
                            WriteBankLogLn(respCode+"："+respInfo);
                            pageResult=true;
                        }
                    }else{
                        WriteBankLogLn(tmpSbMsg.toString());
                        pageResult=true;
                    }
                }else{
                    WriteBankLogLn(resutlt[1]);
                    pageResult=true;
                }
            }
            WriteBankLogLn("总查询回单数："+qryTotalNum+"；总下载回单数："+dowTotalNum+"；数据"+(qryTotalNum==dowTotalNum?"一致":"不一致"));
        } catch (Exception e) {
            WriteBankLogLn(e);
        }
        return null;
    }

    public RetAtsReceipt qryReceiptOneDay_MT(ReceiptProConfig pConfig,ReqQryReceipt pReqReceipt, Date pOneDay) throws Exception {
        return null;
    }

    /**
     * 电子回单查询Pro
     * @param pConfig
     * @param pReqReceipt
     * @param pOneDay
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsReceipt qryReceiptOneDay(ReceiptProConfig pConfig, ReqQryReceipt pReqReceipt, Date pOneDay) throws Exception {
        return "1".equals(getBankConfig().getValueAsString("channelFlag"))?qryReceiptOneDay_Xml(pConfig,pReqReceipt,pOneDay):qryReceiptOneDay_MT(pConfig,pReqReceipt,pOneDay);
    }
}
